from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from configparser import ConfigParser
import time


def load_cookies(config):
    cookies = []
    required_cookies = ["SESSDATA", "bili_jct", "DedeUserID", "DedeUserID__ckMd5", "buvid3"]

    for name in required_cookies:
        if config.has_option('cookies', name):
            cookies.append({
                "name": name,
                "value": config.get('cookies', name),
                "domain": ".bilibili.com",
                "secure": name.lower() in ["sessdata", "bili_jct"]
            })
    return cookies


def load_config():
    config = ConfigParser(interpolation=None)
    config.read('config.ini', encoding='utf-8')

    return {
        "user_agent": config.get('settings', 'user_agent'),
        "target_url": config.get('settings', 'target_url'),
        "cookies": load_cookies(config)
    }


def init_browser(user_agent):
    options = Options()
    options.add_argument(f"user-agent={user_agent}")
    options.add_argument("--disable-blink-features=AutomationControlled")
    return webdriver.Chrome(options=options)


def main():
    config = load_config()
    driver = init_browser(config["user_agent"])

    try:
        driver.get("https://www.bilibili.com")
        time.sleep(1)

        for cookie in config["cookies"]:
            driver.add_cookie(cookie)

        driver.get(config["target_url"])
        print(f"当前URL: {driver.current_url}")
        input("按回车键退出...")

    except Exception as e:
        print(f"发生错误: {e}")
        driver.save_screenshot("error.png")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()